package com.iss.card.view.account;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.iss.card.CardController;
import com.iss.card.CardController.EventType;
import com.iss.card.R;
import com.iss.card.common.ApplicationManager;
import com.iss.card.common.FunctionUtil;
import com.iss.card.common.IBackKeyListener;
import com.iss.card.common.Tools;
import com.iss.card.db.QueryHandlerContract;
import com.iss.card.db.CardContract.Accounts;
import com.iss.card.model.UserInfo;
import com.iss.card.view.model.ResponseBean;
import com.iss.card.webservice.BaseModel;
import com.iss.card.webservice.WebServiceAsyncService;
import com.iss.card.webservice.WebServiceAsyncServiceHelper;
import com.iss.card.webservice.WebServiceAsyncService.Operation;
import com.iss.card.webservice.WebServiceAsyncService.PostExecute;
import com.iss.card.webservice.WebServiceManager.WebServiceRegistrationParameter;
import com.iss.card.webservice.WebServiceManager.WebServiceUrlPortManager;
import com.iss.card.webservice.WebServiceUtils;
import com.iss.card.common.Tools.TimeCount;;

public class AccountRegisterView extends Fragment implements IBackKeyListener,View.OnClickListener{
	
	private final static String TAG = "AccountRegisterView";
	private Activity mContext;
	
	private TextView registerUserName;
	private TextView registerPhoneNum;
	private TextView registerEmail;
	private TextView registerPassword;
	private TextView registerConfirmPassword;
	private TextView registerCaptchaButton;
	private EditText registerCaptchaInput;
	private Button btnConfirm;
	private TimeCount timer;
	
	private LinearLayout mainView;
	private Button btnReturn;
	private ImageButton btnJob;
	private TextView name;
	
	

	
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		this.mContext = activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
		mainView = (LinearLayout) inflater.inflate(R.layout.account_register, null);
		initView();
		return mainView;
	}

	
	
	public void initView(){
		
		
		registerUserName = (TextView) mainView.findViewById(R.id.register_user_name);
		registerPhoneNum = (TextView) mainView.findViewById(R.id.register_phone_num);
		//deleted by qiubo at 2013-03-20 begin
//		registerEmail = (TextView) l.findViewById(R.id.register_user_email);
		//deleted by qiubo at 2013-03-20 end
		registerPassword = (TextView) mainView.findViewById(R.id.register_password);
		registerConfirmPassword = (TextView) mainView.findViewById(R.id.register_confirm_password);
		
		registerCaptchaButton = (TextView) mainView.findViewById(R.id.register_GetCaptcha_button);
		
		btnJob = (ImageButton) mainView.findViewById(R.id.job_button);
		btnReturn = (Button) mainView.findViewById(R.id.return_button);
		name = (TextView) mainView.findViewById(R.id.job_name_val);
		name.setVisibility(View.VISIBLE);
		name.setText(R.string.title_name_register);
		btnJob.setVisibility(View.INVISIBLE);
		btnReturn.setVisibility(View.VISIBLE);
		btnReturn.setOnClickListener(this);
		
		
		registerCaptchaButton.setOnClickListener(this);
		registerCaptchaInput = (EditText)mainView.findViewById(R.id.register_Captcha);
		btnConfirm = (Button) mainView.findViewById(R.id.register_button_confirm);
		btnConfirm.setOnClickListener(this);
		timer = new TimeCount(mContext,60000, 1000, registerCaptchaButton);
		registerPhoneNum.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				registerUserName.setText(s.toString());
			}
		});
	}

	public void registerAccount(){
		String[] objVal = doValidationAndCollect();
		doAccountRegister(objVal);
	}
	
	/*
	 * ��֤�������Ϣ���ռ����
	 */
	private String[] doValidationAndCollect(){
		String userNameVal = registerUserName.getText().toString();
		String userPhoneNum = registerPhoneNum.getText().toString();
//		String email = registerEmail.getText().toString();
		String password = registerPassword.getText().toString();
		String confirmPassword = registerConfirmPassword.getText().toString();
		String captcha = registerCaptchaInput.getText().toString();
		if(TextUtils.isEmpty(userNameVal)){
			Tools.showToast(mContext, R.string.please_write_user_name);
			return null;
		}
		
		if(TextUtils.isEmpty(userPhoneNum) || userPhoneNum.length() != 11){ // ��֤��Ϊ�� ��11λ
			Tools.showToast(mContext, R.string.please_write_true_num);
			return null;
		}
		
		if(TextUtils.isEmpty(password)){
			Tools.showToast(mContext, R.string.please_write_password_not_null);
			return null;
		}
		
		if(TextUtils.isEmpty(confirmPassword) || !password.equals(confirmPassword)){ //�����������벻һ��
			Tools.showToast(mContext, R.string.please_write_double_true);
			registerPassword.setText("");
			registerConfirmPassword.setText("");
			return null;
		}
		
		String[] obj = {userPhoneNum, userNameVal, password, captcha};
		return obj;
	}
	
	/*
	 * ע��
	 */
	private void doAccountRegister(String[] obj){
		
		if(obj == null){
			return;
		}
		final String usrMobile = obj[0];
		final String usrPass = obj[2];
		WebServiceAsyncService asyncService = new WebServiceAsyncService();
		asyncService.setParameterToAsyncService(mContext, 
				asyncService.getNextToken(), 
				Operation.OP_SERVICE_ARG_ACCOUNT_REGISTER, 
				WebServiceRegistrationParameter.PRODUCT_ACCOUNT_REGISTER,
				obj,
				WebServiceUrlPortManager.ACTION_URL_PORT_ACCOUNT_REGISTER,
				this,
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		asyncService.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token, Object envelope,int index) {
				ResponseBean responseBean = WebServiceUtils.getObjectResultToBaseInfo(envelope, BaseModel.class);
				
				if(responseBean.getStatus().equals(ApplicationManager.RESPONSE_OK)){
					Tools.showToast(mContext, R.string.registration_successful);
					doLoginAfterRegisterSucess(usrMobile,usrPass);
				}else{
					Tools.showToast(mContext, responseBean.getMessage());
					return;
				}
			}
		});
	}
	

	@Override
	public void cancelUpdate(Object... params) {
		// TODO Auto-generated method stub
		
	}

	//add by qiubo at 2013-03-21 begin
	@Override
	public void onClick(View view) {	
		switch (view.getId()) {
			case R.id.register_GetCaptcha_button:
				String Mobile = registerPhoneNum.getText().toString().trim();
				if ("".equals(Mobile) || ! Tools.isMobileNO(Mobile)) { //��ȡ��֤��ǰ�Ƿ�Ҫ��֤һЩ�������ݣ�
					Tools.showToast(mContext, R.string.please_write_true_num);
					break;
				}
				String Caller = ApplicationManager.CAPTCHA_FLAG_REGISTER; //1��ע����֤��
				String[] getCaptchaObj = {Mobile, Caller};
				doGetCaptchaAsyncService(getCaptchaObj); 
				
				break;
			case R.id.register_button_confirm:
				registerAccount();
				break;
			case R.id.return_button:
				CardController.getInstance(mContext).sendEvent(EventType.ACTION_RETURN);
				break;
			default:
				break;
		}		
		
	}

	private void doGetCaptchaAsyncService(String[] obj) {
	
		if (obj == null) {
			return;
		}
		
		if(registerCaptchaButton.getText()!= null){
			registerCaptchaButton.setText("");
		}
		
		registerCaptchaButton.setClickable(false);
		WebServiceAsyncService asyncService = new WebServiceAsyncService();
		asyncService.setParameterToAsyncService(mContext, 
				asyncService.getNextToken(),
				Operation.OP_SERVICE_ARG_GET_CAPTCHA,
				WebServiceRegistrationParameter.ACCOUNT_REGISTER_GETCAPTCHA, obj,
				WebServiceUrlPortManager.ACTION_URL_PORT_CHECKING_MESSGE,
				this,
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		asyncService.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token,Object envelope,int index) {
				ResponseBean response = WebServiceUtils.getObjectResultToBaseInfo(envelope, BaseModel.class);
				
				if (response.getStatus() == ApplicationManager.RESPONSE_OK) {
					Tools.showToast(mContext, R.string.textview_achievecaptcha);
					timer.start();
				}else if (response.getMessage().equals(ApplicationManager.GET_STATUS_SCEECSS)){
					Tools.showToast(mContext, R.string.textview_achievecaptcha);
					timer.start();
				}else {
					Tools.showToast(mContext, response.getMessage());
					timer.onFinish();
				}
				
			}
		});
	}
	
	private void doLoginAfterRegisterSucess(String userMobile, String UserPass){
		String obj[] = {userMobile, UserPass};
		JSONObject accountObj;
//		add for auto remember login user password
//		not use yet
		/*try {
			accountObj = new JSONObject(FunctionUtil.getUsrInfoForAutoLogin());
			if(accountObj.has(userMobile)){
				accountObj.remove(userMobile);
				accountObj.put(userMobile, UserPass);
			}else {
				accountObj.put(userMobile, UserPass);
			}
			FunctionUtil.saveUsrInfoForAutoLogin(accountObj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}*/
//		end
		WebServiceAsyncService asyncService = new WebServiceAsyncService();
		asyncService.setParameterToAsyncService(mContext,
				asyncService.getNextToken(),
				Operation.OP_SERVICE_ARG_ACCOUNT_LOGIN,
				WebServiceRegistrationParameter.PRODUCT_ACCOUNT_LOGIN, obj,
				WebServiceUrlPortManager.ACTION_URL_PORT_ACCOUNT_LOGIN, this,
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		asyncService.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token, Object envelope,
					int index) {
				if (envelope == null) {
					Log.e(TAG, "envelope is null");
					return;
				}
				ResponseBean response = WebServiceUtils
						.getObjectResultToBaseInfo(envelope, UserInfo.class);
				ArrayList<UserInfo> accountList = new ArrayList<UserInfo>();
				accountList = (ArrayList<UserInfo>) response.getReturnList();
				if (response.getStatus().equals(ApplicationManager.RESPONSE_OK)) {
					FunctionUtil.saveCurrentLogInUser((UserInfo) accountList
							.get(0));
					new Handler().postDelayed(new Runnable() {
						public void run() {
							mContext.finish();
						}
					}, 2000);

				} else {
					Tools.showToast(mContext, response.getMessage());
					return;
				}
				
			}
		});
	}
}
